package com.example.ayniu.treadmill.fragment;

import android.animation.ValueAnimator;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.ayniu.treadmill.MainActivity;
import com.example.ayniu.treadmill.R;
import com.example.ayniu.treadmill.base.blueInterface;
import com.example.ayniu.treadmill.bluetooth.BluetoothChatService;
import com.example.ayniu.treadmill.util.UserInfoUtil;

import java.text.DecimalFormat;

public class Fragment_main extends Fragment {

	/*public static Spinner mSpinner = null;
	public static int spinner_select;
	public static RelativeLayout distance_layout,time_layout,calories_layout,ordinary_layout;
	public static Button bt_start;
	private Button bt_add_dis,bt_minus_dis,bt_add_cal,bt_minus_cal,bt_add_time,bt_minus_time;
	public static EditText et_aim_dis,et_aim_cal,et_aim_minute,et_aim_hour;*/
	private CountDownTimer mCountDownTimer;
	private TextView tv_countdown;
	private RelativeLayout layout_countdown;
	public Button bt_main_start,bt_main_add,bt_main_minus;
	public static int MAIN_STATUS;			//常规训练的运动状态
	public static int MAIN_STATUS_START = 0;	//初始，待开始
	public static int MAIN_STATUS_STOP = 1;	//进行中，待停止
	public static int MAIN_STATUS_RESET = 2;	//停止，待复位
	//运动数据
	public static TextView main_data_distance,main_data_calories,main_data_speed,main_data_time;

	private Chronometer main_timer_time;
	private int sport_time;
	private int sport_data_minutes = 0;		//显示的运动分钟数
	private float sport_speed_float;    //当前速度
	private float sport_distance_float = 0.0f; //累计距离
	private float sport_calories_float = 0.0f; //累计卡路里

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// ##layout布局文件转化为view

		//resource 需要加载的布局文件
		//root 加载Layout的布局文件的父ViewGroup
		//布尔值变量 :false 不返回父ViewGroup
		View view = inflater.inflate(R.layout.layout_fragment_main, container, false);

		initView(view);

		return view;
	}

	public void initView(View view) {

		MAIN_STATUS = MAIN_STATUS_START;//初始状态为待开始

		main_data_distance = (TextView) view.findViewById(R.id.data_main_distance);
		main_data_calories = (TextView) view.findViewById(R.id.data_main_calories);
		main_data_time = (TextView) view.findViewById(R.id.data_main_time);
		main_data_speed = (TextView) view.findViewById(R.id.data_main_speed);
		main_timer_time = (Chronometer) view.findViewById(R.id.timer_main_time);

		bt_main_start = (Button) view.findViewById(R.id.bt_main_start);
		bt_main_add = (Button) view.findViewById(R.id.bt_main_add);
		bt_main_minus = (Button) view.findViewById(R.id.bt_main_minus);

		//倒计时
		tv_countdown = (TextView) getActivity().findViewById(R.id.tv_countdown);
		layout_countdown = (RelativeLayout) getActivity().findViewById(R.id.layout_countdown);


		bt_main_start.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//根据状态实现不同点击事件
				switch (MAIN_STATUS) {
					case 0: {    //开始倒计时
						if(MainActivity.mChatService.getState()== BluetoothChatService.STATE_CONNECTED)
						mCountDownTimer.start();
						MAIN_STATUS = MAIN_STATUS_STOP;//状态进行中
					}
					break;
					case 1: {
						handler.removeCallbacks(runnable);//暂停线程
						//onRecordPause();//结束计时
						//向设备发出停止运动的请求(A)
						if (getActivity() instanceof MainActivity) {
							MainActivity fca = (MainActivity) getActivity();
							blueInterface blueI = new blueInterface();
							blueInterface.stopReq stopReq = blueI.new stopReq();
							stopReq.msgType = 0;
							//stopReq.usRes = 0;
							byte[] sendData = new byte[512];
							int sendLength = stopReq.createFrame(sendData);
							byte[] realSend = new byte[sendLength];
							sendLength = stopReq.createFrame(realSend);
							fca.sendMessage(realSend, sendLength);
						}
						MAIN_STATUS = MAIN_STATUS_RESET;//状态变为停止中
						bt_main_start.setBackgroundResource(R.drawable.bt_main_reset);
						bt_main_start.setText(getString(R.string.bt_text_reset));
					}
					break;
					case 2: {
						//onRecordStop();//结束计时清零
						MAIN_STATUS = MAIN_STATUS_START;//状态变为进行中
						bt_main_start.setBackgroundResource(R.drawable.bt_main_start);
						bt_main_start.setText(getString(R.string.bt_text_start));
						main_data_speed.setText("0.0");//各数据清零
						main_data_distance.setText("0.000");
						main_data_calories.setText("0");
						main_data_time.setText("0:00");
						sport_time = 0;
						sport_data_minutes = 0;
						sport_speed_float = 0;
						sport_distance_float = 0.0f;
						sport_calories_float = 0.0f;
					}
					break;
					default:
						break;

				}

			}
		});

		//开始倒计时的实现
		mCountDownTimer = new CountDownTimer(4000, 1000) {
			int i = 3;
			@Override
			public void onTick(long millisUntilFinished) {
				layout_countdown.setVisibility(View.VISIBLE);
				tv_countdown.setText(i + "");
				if(i == 3) {
					if (getActivity() instanceof MainActivity) {
						MainActivity fca = (MainActivity) getActivity();
						blueInterface blueI = new blueInterface();
						blueInterface.startReq startReq = blueI.new startReq();
						startReq.msgType = 0;
						startReq.workType = 0;
						byte[] sendData = new byte[512];
						int sendLength = startReq.createFrame(sendData);
						byte[] realSend = new byte[sendLength];
						sendLength = startReq.createFrame(realSend);
						fca.sendMessage(realSend, sendLength);
					}
				}
				i--;
				dimBackground(1.0f, 0.5f);
			}

			@Override
			public void onFinish() {
				i = 3;
				dimBackground(0.5f, 1.0f);
				mCountDownTimer.cancel();
				layout_countdown.setVisibility(View.GONE);
				//开始运动
				main_data_speed.setText("0.0");//初始速度的值
				bt_main_start.setBackgroundResource(R.drawable.bt_main_stop);
				bt_main_start.setText(getString(R.string.bt_text_stop));
				//onRecordStart();//开始运动计时
				//向设备发出开始运动的请求(A)
				/*
				if (getActivity() instanceof MainActivity) {
					MainActivity fca = (MainActivity) getActivity();
					blueInterface blueI = new blueInterface();
					blueInterface.startReq startReq = blueI.new startReq();
					startReq.msgType = 0;
					startReq.workType = 0;
					byte[] sendData = new byte[512];
					int sendLength = startReq.createFrame(sendData);
					byte[] realSend = new byte[sendLength];
					sendLength = startReq.createFrame(realSend);
					fca.sendMessage(realSend, sendLength);
				}
				*/
				handler.post(runnable);//开启运动界面数据更新
			}
		};

		bt_main_add.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(sport_speed_float < 10 && MAIN_STATUS == MAIN_STATUS_STOP) {
					//向设备发出速度增加的请求(A)
					if (getActivity() instanceof MainActivity) {
						MainActivity fca = (MainActivity) getActivity();
						blueInterface blueI = new blueInterface();
						blueInterface.speedReq speedReq = blueI.new speedReq();
						String str_type = "0-pluss";
						speedReq.type = 0;
						speedReq.speedLev = 0;
						speedReq.usRes = 0;
						byte[] sendData = new byte[512];
						int sendLength = speedReq.createFrame(sendData);
						byte[] realSend = new byte[sendLength];
						sendLength = speedReq.createFrame(realSend);
						if(UserInfoUtil.thisSpeed < 80) {
							fca.sendMessage(realSend, sendLength);
						}
					}
				}
			}
		});
		bt_main_minus.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if(sport_speed_float < 10 && MAIN_STATUS == MAIN_STATUS_STOP) {
					//向设备发出速度增加的请求(A)
					if (getActivity() instanceof MainActivity) {
						MainActivity fca = (MainActivity) getActivity();
						blueInterface blueI = new blueInterface();
						blueInterface.speedReq speedReq = blueI.new speedReq();
						String str_type = "1-minus";
						speedReq.type = 1;
						speedReq.speedLev = 0;
						speedReq.usRes = 0;
						byte[] sendData = new byte[512];
						int sendLength = speedReq.createFrame(sendData);
						byte[] realSend = new byte[sendLength];
						sendLength = speedReq.createFrame(realSend);
						if(UserInfoUtil.thisSpeed > 5) {
							fca.sendMessage(realSend, sendLength);
						}
					}
				}
			}
		});


	}

	//实现数据随运动时间而动态更新
	public android.os.Handler handler = new android.os.Handler();
	public Runnable runnable = new Runnable() {
		@Override
		public void run() {
			//向设备请求运动参数(A)

			try {
				Thread.currentThread().sleep(2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if(MAIN_STATUS == MAIN_STATUS_STOP){
				if (getActivity() instanceof MainActivity) {
					MainActivity fca = (MainActivity) getActivity();
					blueInterface blueI = new blueInterface();
					blueInterface.paraGetReq paraGetReq = blueI.new paraGetReq();
					//paraGetReq.usRes = ;
					byte[] sendData = new byte[512];
					int sendLength = paraGetReq.createFrame(sendData);
					byte[] realSend = new byte[sendLength];
					sendLength = paraGetReq.createFrame(realSend);
					fca.sendMessage(realSend, sendLength);
				}
			}
			handler.postDelayed(runnable, 1000);
			/*//从timer_addup获取已运动时间(单位：秒钟s)
			sport_time = (int)(SystemClock.elapsedRealtime()- main_timer_time.getBase())/1000;
			if(sport_time % 60 == 0 && sport_time != 0) {
				sport_data_minutes++;//将秒化为分钟数显示
			}
			//各参数
			sport_speed_float = Float.parseFloat(main_data_speed.getText().toString());          //获取当前速度（单位：km/h）
			sport_distance_float = sport_distance_float + (sport_speed_float/3600);             //累计距离 = 原距离 + 速度(km/s)X1s  每秒刷新一次
			sport_calories_float = sport_calories_float + 0.1f;                                 //累计卡路里（算法公式不准确，待改进）
			//main_data_distance.setText(new DecimalFormat("#0.00").format(sport_distance_float)+"");
			//Log.i("dis",sport_distance_float+"="+(sport_distance_float-(sport_speed_float/3600))+"+"+(sport_speed_float/3600));
			main_data_calories.setText(new DecimalFormat("#0").format(sport_calories_float)+"");
			//Log.i("cal", sport_calories_float+"");
			if(sport_data_minutes < 10) {
				main_data_time.setText("0" +sport_data_minutes);
			}else{
				main_data_time.setText(sport_data_minutes);
			}*/
		}
	};

	/*//运动几时
	private long recordingTime = 0;// 记录下来的总时间
	public void onRecordStart() {
		main_timer_time.setBase(SystemClock.elapsedRealtime() - recordingTime);// 跳过已经记录了的时间，起到继续计时的作用
		*//*int hour = (int) ((SystemClock.elapsedRealtime()-timer_addup.getBase()) / 1000 / 60 / 60);//毫秒转换为小时
		if(hour==0)timer_addup.setFormat("0"+String.valueOf(hour)+":%s");*//*
		main_timer_time.start();
	}
	public void onRecordPause() {
		main_timer_time.stop();
		recordingTime = SystemClock.elapsedRealtime()- main_timer_time.getBase();// 保存这次记录了的时间
	}
	public void onRecordStop() {
		recordingTime = 0;
		main_timer_time.stop();
		main_timer_time.setBase(SystemClock.elapsedRealtime());
	}*/

	//屏幕变暗的实现方法
	private void dimBackground(final float from, final float to) {
		final Window window = getActivity().getWindow();
		ValueAnimator valueAnimator = ValueAnimator.ofFloat(from, to);
		valueAnimator.setDuration(500);
		valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
			@Override
			public void onAnimationUpdate(ValueAnimator animation) {
				WindowManager.LayoutParams params = window.getAttributes();
				params.alpha = (Float) animation.getAnimatedValue();
				window.setAttributes(params);
			}
		});
		valueAnimator.start();
	}
}
